package cn.sofwin.boot.crud.service.impl;

import cn.sofwin.boot.crud.dto.LoginParams;
import cn.sofwin.boot.crud.dto.LoginResult;
import cn.sofwin.core.support.api.GenericStatusCode;
import cn.sofwin.core.support.api.StatusCode;
import cn.sofwin.core.support.utils.Encodes;
import net.bytebuddy.asm.Advice;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import cn.sofwin.core.mvc.bean.Meta;
import cn.sofwin.core.mvc.annotation.BaseDao;
import cn.sofwin.core.mvc.service.impl.BaseServiceImpl;
import cn.sofwin.boot.crud.entity.BaUser;
import cn.sofwin.boot.crud.dao.BaUserDao;
import cn.sofwin.boot.crud.service.BaUserService;

import java.util.concurrent.TimeUnit;

/**
 * 服务层
 * @author LetCode
 * @since 1.0
 *
 */
@CacheConfig(cacheNames = "baUser")
@Service("baUserService")
public class BaUserServiceImpl extends BaseServiceImpl<BaUser> implements BaUserService {
	
	@BaseDao
	@Autowired
	BaUserDao baUserDao;

	@Autowired
	RedisTemplate<String,Object> redisTemplate;

	@Cacheable
	@Override
	public Meta loadMetaInfo(){
		Meta meta = new Meta("", "baUser");

		// 增加表头字段信息
		meta.addColumn("id", "序号")
		      .addColumn("username", "用户名")
		      .addColumn("password", "密码")
		      .addColumn("nickname", "昵称")
		      .addColumn("addTime", "添加时间")
		      .addColumn("status", "状态：-1删除，0冻结，1正常");

		return meta;
	}

	@Override
	public LoginResult login(LoginParams loginParams) {
		LoginResult loginResult = new LoginResult();
		BaUser user = baUserDao.selectByUsername(loginParams.getUsername());

		StatusCode statusCode = GenericStatusCode.Success;
		if (user == null) {
			statusCode =GenericStatusCode.UsernameError;
		}else {
			if(user.getPassword().equals(loginParams.getPassword())){
				//生成Token，添加缓存
				String token = Encodes.nonceString(32);
				String key = "LOGIN_TOKEN_" + token;
				user.setPassword(null);
				redisTemplate.opsForValue().set(key,user,30, TimeUnit.MINUTES);
				loginResult.setToken(token);
			}else{
				statusCode = GenericStatusCode.PasswordError;

			}
		}
		loginResult.setStatusCode(statusCode);
		return loginResult;
	}
	
}